package com.yuanchu.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.utils.DateFormatUtils;
import com.yuanchu.common.utils.PageResult;
import com.yuanchu.common.utils.PageUtils;
import com.yuanchu.common.utils.Query;
import com.yuanchu.store.dao.YoshopUserPointsLogDao;
import com.yuanchu.store.entity.YoshopUserPointsLogEntity;
import com.yuanchu.store.service.YoshopUserPointsLogService;
import com.yuanchu.store.service.YoshopUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.List;
import java.util.Map;




@Service("yoshopUserPointsLogService")
public class YoshopUserPointsLogServiceImpl extends ServiceImpl<YoshopUserPointsLogDao, YoshopUserPointsLogEntity> implements YoshopUserPointsLogService {


    @Resource
    private YoshopUserService userService;


    public PageUtils queryPage(Map<String, Object> params) {
        IPage<YoshopUserPointsLogEntity> page = this.page(
                new Query<YoshopUserPointsLogEntity>().getPage(params),
                new QueryWrapper<YoshopUserPointsLogEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageResult<YoshopUserPointsLogEntity> queryUserPointsLog(Integer userId, Integer page) {
        LambdaQueryWrapper<YoshopUserPointsLogEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YoshopUserPointsLogEntity::getUserId, userId);
        // 全部
        if (page == null || page == 0){
            page = 1;
        }
        lqw.orderByDesc(YoshopUserPointsLogEntity::getCreateTime);
        Page<YoshopUserPointsLogEntity> page1 = new Page<>(page, 15);
        Page<YoshopUserPointsLogEntity> page_result = this.page(page1, lqw);
        List<YoshopUserPointsLogEntity> records = page_result.getRecords();
        records.forEach(userLog -> userLog.setCreateTime(DateFormatUtils.formatDatetime(userLog.getCreateTime())));

        PageResult<YoshopUserPointsLogEntity> result = new PageResult<>();
        result.setTotal(Math.toIntExact(page_result.getTotal()));
        result.setCurrentPage(page);
        result.setData(records);
        result.setPerPage(15);
        long total = page_result.getTotal();
        // 计算总页数，向下取整避免超出实际页数（这里已假设pageInfo.getTotal()返回的是long类型）
        int totalPages = (int) Math.ceil((double) total / 15);
        result.setLastPage(totalPages);

        return result;
    }

    @Override
    public boolean decrUserPoints(Integer userId, Integer scene, Integer points, String orderNo, Integer storeId) {
        if (points == null){
            return false;
        }
        YoshopUserPointsLogEntity userPointsLog = new YoshopUserPointsLogEntity();
        userPointsLog.setUserId(userId);
        userPointsLog.setStoreId(storeId);
        userPointsLog.setValue("-"+points);
        // 余额变动场景(10用户充值 20用户消费 30管理员操作 40订单退款)
        if (scene == 20){
            userPointsLog.setDescribe("用户消费："+orderNo);
        }else if (scene == 30){
            userPointsLog.setDescribe("管理员 ["+userId + "]操作");
        }
        userPointsLog.setCreateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        return this.save(userPointsLog);
    }

    @Override
    public boolean bonusUserPoints(Integer userId, Integer pointsBonus, String orderNo, Integer storeId) {
        YoshopUserPointsLogEntity userPointsLog = new YoshopUserPointsLogEntity();
        userPointsLog.setUserId(userId);
        userPointsLog.setStoreId(storeId);
        userPointsLog.setValue(String.valueOf(pointsBonus));
        userPointsLog.setStoreId(storeId);
        // 余额变动场景(10用户充值 20用户消费 30管理员操作 40订单退款)
        userPointsLog.setDescribe("消费赠送："+orderNo);
        userPointsLog.setCreateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        boolean save = this.save(userPointsLog);
        if (!save){
            return false;
        }
        // 修改用户积分
        boolean userPoints = userService.updateUserPoints(userId, pointsBonus, storeId);
        if (!userPoints){
            return false;
        }
        return true;

    }
}